Components.utils.import("resource://gre/modules/JSON.jsm");

var EXPORTED_SYMBOLS = [
    "lucidapi"
]

function lucid_safeclose(closeable)
{
    try
    {
        closeable.close();
    }
    catch (e)
    {
        Components.utils.reportError(e);
        if (e.stack)
            Components.utils.reportError(e.stack);
    }
}

function lucid_getContent( aURL )
{
    var retval = "";
    try
    {
        var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces["nsIIOService"]);
        var channel = ioService.newChannel(aURL, null, null);
        var input = channel.open();
        var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces["nsIConverterInputStream"]);
        cstream.init(input, "UTF-8", 1024, 0xFFFD);
        var str = {};
        while (cstream.readString(1024, str) != 0) {
            retval += str.value;
        }
    }
    finally
    {
        lucid_safeclose(cstream);
        lucid_safeclose(input);
    }
    return retval;
};

(function(){

    function lucid_loadScript( scripts, context )
    {
        if (typeof(scripts) == "string")
        {
            scripts = [scripts];
        }
        var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces["mozIJSSubScriptLoader"]);
        var retval = undefined;
        for (var ii = 0; ii < scripts.length; ii++)
        {
            try {
                retval = loader.loadSubScript('chrome://lucidity/content/' + scripts[ii], context);
            } catch (e) { }
        }
        return retval;
    }

    var scriptlist = lucid_getContent("chrome://lucidity/content/modules/scripts.txt");
    scriptlist = scriptlist.split("\n");
    var scriptarr = [];
    for (var ii = 0; ii < scriptlist.length;ii++)
    {
        var scriptpath = scriptlist[ii];
        if (scriptpath.length > 0)
            scriptarr.push("modules/" + scriptpath);
    }
    scriptarr.push("xpcom/lucidxlib.js");
//    scriptarr.push("xpcom/googleapi.js");
    scriptarr.push("test/lucidtest.js");
    lucid_loadScript(scriptarr,this);
})();

lucidapi.getContent = lucid_getContent;
